package com.op.parcel.boot.support;

import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.micrometer.core.instrument.util.StringUtils;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * 查询工具
 *
 * @author xuan🐽
 */
public class Condition {

	/**
	 * 分页查询
	 *
	 * @param query
	 * @return
	 */
	public static <T> IPage<T> getPage(Query query) {
		Page<T> page = new Page<>(query.getCurrent() == null ? 1 : query.getCurrent(), query.getSize() == null ? 1 : query.getSize());
		if (StringUtils.isNotEmpty(query.getAscs())) {
			page.setAsc(query.getAscs().split(","));
		}
		if (StringUtils.isNotEmpty(query.getDescs())) {
			page.setDesc(query.getDescs().split(","));
		}
		return page;
	}

	/**
	 * 对象查询
	 *
	 * @param entity
	 * @param <T>
	 * @return
	 */
	public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
		return new QueryWrapper<>(entity);
	}

	/**
	 * 条件查询
	 * @param query
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) {
		query.remove("current");
		query.remove("size");
		QueryWrapper<T> qw = new QueryWrapper<>();
		qw.setEntity(BeanUtils.instantiateClass(clazz));
		if (ObjectUtils.isEmpty(query)) {
			query.forEach((k, v) -> {
				if (!ObjectUtils.isEmpty(v)) {
					qw.like(humpToUnderline(k), v);
				}
			});
		}
		return qw;
	}

	private static String humpToUnderline(String para) {
		StringBuilder sb = new StringBuilder(para);
		int temp = 0;

		for(int i = 0; i < para.length(); ++i) {
			if (Character.isUpperCase(para.charAt(i))) {
				sb.insert(i + temp, "_");
				++temp;
			}
		}

		return sb.toString().toLowerCase();
	}
}
